package com.tc.have_a_tired;

import com.tc.have_a_tired.service.RestReminderService;
import com.tc.have_a_tired.ui.SystemTrayManager;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.swing.*;
import java.awt.*;

/**
 * 休息提醒应用主类
 */
@SpringBootApplication
public class HaveATiredApplication {

	private static RestReminderService reminderService;
	private static SystemTrayManager trayManager;
	private static JFrame mainFrame;

	public static void main(String[] args) {
		// 设置系统外观
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			// 确保按钮可以显示自定义背景颜色
			UIManager.put("Button.background", null);
			UIManager.put("Button.foreground", null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 在EDT线程中初始化GUI
		EventQueue.invokeLater(() -> {
			try {
				initializeApplication();
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null,
						"应用启动失败: " + e.getMessage(),
						"错误",
						JOptionPane.ERROR_MESSAGE);
			}
		});

		// 启动Spring Boot（如果需要的话，但桌面应用可能不需要）
		// SpringApplication.run(HaveATiredApplication.class, args);
	}

	/**
	 * 初始化应用
	 */
	private static void initializeApplication() {
		// 创建主窗口（隐藏，仅用于系统托盘）
		mainFrame = new JFrame("休息提醒");
		mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		mainFrame.setUndecorated(true);
		mainFrame.setVisible(false);

		// 创建提醒服务
		reminderService = new RestReminderService();
		reminderService.start();

		// 创建系统托盘
		trayManager = new SystemTrayManager(reminderService, mainFrame);
		boolean trayCreated = trayManager.createTrayIcon();

		if (trayCreated) {
			// 显示启动通知
			trayManager.showNotification("休息提醒", "应用已启动，将在后台运行");
		} else {
			// 如果系统托盘不支持，显示主窗口
			mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			mainFrame.setVisible(true);
			mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
				@Override
				public void windowClosing(java.awt.event.WindowEvent windowEvent) {
					if (reminderService != null) {
						reminderService.stop();
					}
					System.exit(0);
				}
			});
			JOptionPane.showMessageDialog(mainFrame,
					"系统托盘不支持，应用将在窗口中运行。\n关闭窗口即可退出程序。",
					"提示",
					JOptionPane.INFORMATION_MESSAGE);
		}

		// 添加关闭钩子
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			if (reminderService != null) {
				reminderService.stop();
			}
			if (trayManager != null) {
				trayManager.removeTrayIcon();
			}
		}));
	}
}
